package cn.wizzer.app.web.modules.controllers.platform.user;

import cn.wizzer.app.sys.modules.services.SysParamService;
import cn.wizzer.app.user.modules.models.UserRestriction;
import cn.wizzer.app.user.modules.services.UserRestrictionService;
import cn.wizzer.app.user.modules.services.UserService;
import cn.wizzer.app.web.commons.ulog.annotation.SLog;
import cn.wizzer.app.web.commons.utils.StringUtil;
import cn.wizzer.framework.base.Result;
import com.alibaba.dubbo.config.annotation.Reference;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.nutz.dao.Chain;
import org.nutz.dao.Cnd;
import org.nutz.dao.util.cri.Exps;
import org.nutz.integration.jedis.RedisService;
import org.nutz.ioc.loader.annotation.Inject;
import org.nutz.ioc.loader.annotation.IocBean;
import org.nutz.lang.Strings;
import org.nutz.lang.Times;
import org.nutz.log.Log;
import org.nutz.log.Logs;
import org.nutz.mvc.annotation.At;
import org.nutz.mvc.annotation.Ok;
import org.nutz.mvc.annotation.Param;


@IocBean
@At("/platform/user/restriction")
public class RestrictionController {
    private static final Log log = Logs.get();

    @Reference
    @Inject
    private SysParamService sysParamService;

    @Inject
    @Reference
    private UserService userService;

    @Inject
    private RedisService redisService;

    @Inject
    @Reference
    private UserRestrictionService restrictionService;


    @At("/")
    @Ok("beetl:/platform/user/restriction/index.html")
    @RequiresPermissions("user.restriction")
    public void index() {

    }

    @At
    @Ok("json:full")
    @RequiresPermissions("user.restriction")
    public Object data(@Param("searchKeyword") String searchKeyword,
                       @Param("pageNumber") int pageNumber,
                       @Param("pageSize") int pageSize) {
        return Result.success(restrictionService.listPage(pageNumber, pageSize, searchKeyword));
    }


    /**
     * 修改
     *
     * @param restriction UserRestriction
     * @return Object
     */
    @At("/editDo")
    @Ok("json")
    @RequiresPermissions("user.restriction.edit")
    @SLog(tag = "修改", msg = "用户ID:${args[1].getAttribute('userId')}")
    public Object editDo(@Param("..") UserRestriction restriction) {

        //返点验证
        double totalRateMax = sysParamService.fetch().getTotalRateMax();
        double selfRateMax = sysParamService.fetch().getSelfRateMax();
        double superRateMax = sysParamService.fetch().getSuperRateMax();
        if (restriction.getSelfRate() > selfRateMax) {
            Result.breakWith("个人返点最大值为：" + selfRateMax / 100 + "%");
        } else if (restriction.getSuperRate() > superRateMax) {
            Result.breakWith("代理返点最大值为：" + superRateMax / 100 + "%");
        } else if ((restriction.getSelfRate() + restriction.getSuperRate()) > totalRateMax) {
            Result.breakWith("总返点最大值为：" + totalRateMax / 100 + "%");
        }

        restriction.setOpAt(Times.getTS());
        restriction.setOpBy(StringUtil.getPlatformUid());
        UserRestriction userRestriction = restrictionService.insertOrUpdate(restriction);
        //保存缓存
        restrictionService.saveCache(userRestriction);
        return Result.success();
    }


    /*
     * 禁用单独限制使用默认
     * @param id String
     * @return Object
     */
    @At("/disable")
    @Ok("json")
    @RequiresPermissions("user.restriction.edit")
    public Object delete(String id, boolean flag) {
        restrictionService.update(
                Chain.make("disabled", flag)
                        .add("opAt", Times.getTS())
                        .add("opBy", StringUtil.getPlatformUid()),
                Cnd.where("id", "=", id));
        return Result.success();
    }

    @At("/showRestriction")
    @Ok("json")
    @RequiresPermissions("user.restriction")
    public Result showRestriction(@Param("userId") String userId) {
        Cnd cnd = Strings.isEmpty(userId) ? Cnd.where(Exps.isNull("user_id")) : Cnd.where("user_id", "=", userId);
        return Result.success(restrictionService.fetch(cnd));
    }

    @At("/editRestriction")
    @Ok("json")
    @RequiresPermissions("user.restriction.edit")
    public Result editRestriction(@Param("..") UserRestriction restriction) {
        UserRestriction userRestriction = restrictionService.insertOrUpdate(restriction);
        //保存缓存
        restrictionService.saveCache(userRestriction);
        return Result.success();
    }

    /**
     * 批量恢复默认限制
     *
     * @param ids
     * @return
     */
    @At("/batchRestriction")
    @Ok("json")
    @RequiresPermissions("user.restriction.edit")
    public Result batchRestriction(@Param("ids") String[] ids) {
        if(ids.length > 0){
            restrictionService.batchRestriction(ids, StringUtil.getPlatformUid());
        }
        return Result.success();
    }

}
